package cn.wolfcode.service.impl;

import cn.wolfcode.domain.StrategyTheme;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.repsitory.StrategyThemeRepsitory;
import cn.wolfcode.service.IStrategyThemeService;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: StrategyTheme业务逻辑实现类
 * @Author: 伍家钰
 * @Date: 2020/8/7 16:20
 * @Version: 1.0
 */
@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Resource
    private StrategyThemeRepsitory strategyThemeRepsitory;
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepsitory.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepsitory.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepsitory.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepsitory.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        List<StrategyTheme> themes = strategyThemeRepsitory.findAll();
        return themes;
    }


    @Override
    public Page<StrategyTheme> query(QueryObject qo) {
        Query query = new Query();
        // 总数据
        long total = mongoTemplate.count(query, StrategyTheme.class);
        if (total == 0) {
            // 如果返回null会报错
            return Page.empty();
        }

        // 当前页显示的数据,Pageable是PageRequest的父接口的父接口
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);
        return new PageImpl<>(list, pageable, total);
    }

}
